<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="formData.username" placeholder="请输入账号如：@idrisla56079731" />
      </el-form-item>
       <el-form-item label="账号类型" prop="accountTypeId">
        <el-select
          v-model="formData.accountTypeId"
          placeholder="请选择账号类型"
          clearable
        >
          <el-option
            v-for="type in accountTypeList"
            :key="type.id"
            :label="type.name"
            :value="type.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入昵称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InternetAccountApi, InternetAccountVO } from '@/api/member/internetaccount'
import { AccountTypeApi, AccountTypeVO } from '@/api/member/accounttype' // 引入账号类型API

/** 互联网账号 表单 */
defineOptions({ name: 'InternetAccountForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const accountTypeLoading = ref(false) // 账号类型加载状态
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const curEditPersonId = ref('') // 修改的人员id
const accountTypeList = ref<AccountTypeVO[]>([]) // 账号类型列表

// 1. 定义表单数据的接口，明确每个字段的类型
interface FormData {
  id?: number; // 可选的number类型
  accountTypeId?: number; // 可选的number类型（账号类型ID通常是number）
  username?: string; // 可选的string类型
  nickname?: undefined; // 昵称
  personId?: string; // 关键：允许string或undefined
}

const formData = ref<FormData>({
  id: undefined,
  accountTypeId: undefined,
  username: undefined,
  nickname: undefined,
  personId: undefined
})
const formRules = reactive({
  username: [{ required: true, message: '账号如：@idrisla56079731不能为空', trigger: 'blur' }],
  accountTypeId: [{ required: true, message: '账号类型不能为空', trigger: 'change' }] // 改为change触发
})
const formRef = ref() // 表单 Ref

// 获取账号类型列表
const getAccountTypeList = async () => {
  accountTypeLoading.value = true
  try {
    const response = await AccountTypeApi.getAccountTypePage({ pageSize: 100 })
    accountTypeList.value = response.list
  } catch (error) {
    message.error('获取账号类型失败')
    console.error('获取账号类型失败:', error)
  } finally {
    accountTypeLoading.value = false
  }
}

/** 打开弹窗 */
const open = async (type: string, editPersonId: string, id?: number) => {
  // 先获取账号类型列表
  await getAccountTypeList()

  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  curEditPersonId.value = editPersonId
  formData.value.personId = editPersonId // 同步到表单数据中
  console.log('editPersonId === >', editPersonId);
  resetForm()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await InternetAccountApi.getInternetAccount(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    formData.value.personId = curEditPersonId.value // 同步到表单数据中
    const data = formData.value as unknown as InternetAccountVO
    if (formType.value === 'create') {
      await InternetAccountApi.createInternetAccount(data)
      message.success(t('common.createSuccess'))
    } else {
      await InternetAccountApi.updateInternetAccount(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    accountTypeId: undefined,
    username: undefined,
    personId: undefined
  }
  formRef.value?.resetFields()
}
</script>
